<style scoped>
</style>
<template>
  <van-field v-bind="$attrs"
             :placeholder="placeholder"
             :model-value="content"
             readonly
             :is-link="!is_info"
             @click="click"  >
    <template #extra>
      <input v-if="!is_info" type="hidden" :name="name" :value="modelValue">
    </template>
  </van-field>
</template>

<script>
import {ajax} from "@/js/api_tool.js";
import {S94Model} from "@/js/S94Model.js";
import tool from "@/js/tool.js";

export default {
  name: "sku",
  props: {
    name: String,
    modelValue: [String,Number],
    config: [String,Object],
    placeholder: String,
    is_info: Boolean,
  },
  emits: ['update:modelValue','change'],
  data(){
    return {
      need_display: true, //定义当modelValue变动时是否需要渲染，用来阻止当前组件变动 modelValue 后重新渲染

      sku_config: {
        group: [],
        list: [],
        num: 1,
        sku_id: this.modelValue,
        switch_stock: false,
        input_num: false,
      },
    }
  },
  methods: {
    display(){
      let config = this.config;
      if (!config) return;
      if (typeof config === 'string'){
        let arr = config.split(':');
        config = {
          model_name: arr[0] || '',
          id: arr[1] || 0
        }
      }else if (typeof config === 'object') {
      }
      this.sku_config.min_price = config.min_price || -1;
      if (config.model_name && config.id>0){
        let model = S94Model.find(config.model_name);
        this.sku_config.switch_stock = model && model.switch_stock;
        ajax(`/home/index/sku_config?model_name=${config.model_name}&id=${config.id}`, (res)=>{
          this.sku_config.group = res.data.group;
          this.sku_config.list = res.data.list;
        })
      }
    },
    click(){
      if (this.is_info) return;
      this.sku_config.sku_id = this.modelValue;
      console.log(this.sku_config);

      tool.select_sku(this.sku_config.group, this.sku_config.list, this.sku_config.switch_stock, this.sku_config.sku_id, this.sku_config.num).then((sku)=>{
        this.change(sku.id);
      })
    },
    change(val){
      this.need_display = false;
      setTimeout(()=>{this.need_display=true},10)
      this.$emit('update:modelValue', val);
      this.$emit('change', val);
    }
  },
  watch: {
    config(v){
      this.display();
    },
    modelValue(){
      if (this.need_display) this.display();
    },
  },
  computed: {
    content(){
      let list = this.sku_config.list;
      if (!list || !list.length) return this.modelValue;
      let sku = list.find(row=>{ return row.id==this.modelValue; });
      return sku ? sku.title : this.modelValue;
    },
  },
  mounted() {
    this.display();
  }
}
</script>